﻿#include "myinifile.h"

void QMyIniFile::clear()
{
    if (m_psettings)
    {
        m_psettings->clear();
        delete m_psettings;
    }
}

QMyIniFile::QMyIniFile()
{
    m_psettings = nullptr;
}

QMyIniFile::~QMyIniFile()
{
    clear();
}

bool QMyIniFile::Open(const QString &fileName)
{
    clear();
    m_psettings = new QSettings(fileName, QSettings::Format::IniFormat);
    this->changeCodec(nullptr);
    return true;
}

bool QMyIniFile::changeCodec(QTextCodec *codec)
{
    if (!codec) {
        m_cfg_codec = QTextCodec::codecForName("UTF-8");
        m_psettings->setIniCodec(m_cfg_codec);
    }
    else {
        m_cfg_codec = codec;
        m_psettings->setIniCodec(m_cfg_codec);
    }
    return true;
}

QVariant QMyIniFile::GetValue(const QString &qstrSegName, const QString &qstrKeyName, const QVariant& defaultValue)
{
    // 以下注释，在 Qt 5.14.2 下
    QStringList segList = m_psettings->childGroups();
    QVariant varRet;
    bool bFind = false;

    foreach(QString segment, segList) // 分析 段
    {
        QByteArray baSeg = segment.toLatin1(); // Windows 下是需要这样的转换，其他平台……
        QString qstrSeg = QString::fromUtf8(baSeg);
        if (qstrSegName == qstrSeg)
        {
            m_psettings->beginGroup(segment);
            QStringList keyList = m_psettings->childKeys();

            foreach(QString key, keyList)// 分析 键
            {
                QByteArray bakey = key.toLatin1(); // Windows 下是需要这样的转换，其他平台……
                QString qstrKey = QString::fromUtf8(bakey);
                if (qstrKeyName == qstrKey)// 分析 值
                {
                    varRet = m_psettings->value(key);// 这里却不需要转换了
                    if (varRet == QVariant()){
                        varRet = defaultValue;
                    }
                    bFind = true;
                    break;
                }
            }
            if (bFind)
                break;
        }
    }
    QString strGroup = m_psettings->group();
    m_psettings->endGroup();
    strGroup = m_psettings->group();

    return varRet;//QVariant();
}

bool QMyIniFile::SetValue(const QString &qstrSegName, const QString &qstrKeyName, const QVariant& qValue)
{
    QString strSegName = QString::fromLatin1(qstrSegName.toUtf8());
    QString strKeyName = QString::fromLatin1(qstrKeyName.toUtf8());
    //m_psettings->setValue(QString("%1/%2").arg(qstrSegName).arg(qstrKeyName), qValue);
    m_psettings->setValue(QString("%1/%2").arg(strSegName).arg(strKeyName), qValue);
    m_psettings->sync();
    return true;
}
